import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MenuItem, TreeNode, AutoComplete, Message } from 'primeng/primeng';
import { MdlSnackbarService } from '@angular-mdl/core';
import { flyIn } from '../../common/animation/common.animation';
import { RoleService } from '../role/service/role.service';
import { HumanService } from './service/human.service';

@Component({
    selector: 'human-role',
    templateUrl: './human-role.component.html',
    styleUrls: ['./human-role.component.scss'],
    providers: [HumanService, RoleService],
    animations: [flyIn]
})
export class HumanRoleComponent implements OnInit {
    humanItem: any = {};
    unitRoles: TreeNode[];
    selectedNodes: TreeNode[] = new Array<TreeNode>();
    selectedRoleNodes: TreeNode[] = new Array<TreeNode>();
    suggestions: TreeNode[];
    suggestion: TreeNode;
    filterStr: string;
    cols: any[] = [{ field: 'label', header: '岗位名称' }]
    @Input()
    set human(human: any) {
        if (!human) return;
        this.humanItem = human;
        this.selectedRoleNodes = [];
        this.roleService.getUnitRoleTree(0, true).subscribe(data => {
            this.unitRoles = data;
            this.humanService.getRolesByHuman(+this.humanItem.humanId).subscribe(data => {
                this.selectedNodes = [];
                data.forEach(ele => {
                    this.recursionExpendSuggestionTreeNode(this.unitRoles, ele['unitCode'] + ele['roleId'] + '/');
                });
            })
        });
    }
    get human(): any { return this.humanItem; }

    constructor(
        private mdlSnackbarService: MdlSnackbarService,
        private humanService: HumanService,
        private roleService: RoleService) { }

    ngOnInit() {
    }

    /** 人员岗位保存事件 */
    save($event) {
        let selectedHumanIds = [];
        this.selectedRoleNodes.forEach((ele, i) => selectedHumanIds.push(ele['id'].replace('HUMAN_', '')));
        let roleHumans = { 'humanRoleId': this.humanItem.humanId, 'ids': selectedHumanIds };
        this.humanService.saveUpdateHumanRoles(roleHumans)
            .subscribe(data => this.mdlSnackbarService.showToast('数据保存成功！'));
    }

    /** 树节点展开事件 */
    unitNodeExpand(event) {
        if (event.node && event.node.children.length == 0) {
            let unitId = +event.node.id.replace('UNIT_', '');
            this.roleService.getUnitRoleTree(unitId, false).subscribe(nodes => event.node.children = nodes);
        }
    }

    /** 树节点选中事件 */
    nodeSelect(event) {
        this.selectedRoleNodes = [];
        this.selectedNodes.forEach((node, i) => {
            if (node.data['type'] == 'R') {
                this.selectedRoleNodes.push(node);
            }
        });
    }

    /** 树节点取消选中事件 */
    nodeUnSelect(event) {
        this.selectedRoleNodes = [];
        this.selectedNodes.forEach((node, i) => {
            if (node.data['type'] == 'R') {
                this.selectedRoleNodes.push(node);
            }
        });
    }

    /**  岗位查找 */
    search(event) {
        if (!event.query) return;
        this.roleService.searchUnitRoleByName(event.query).subscribe(data => {
            this.suggestions = data;
        });
    }

    /**选择下拉事件 */
    selectSuggestion() {
        this.recursionExpendSuggestionTreeNode(this.unitRoles, this.suggestion['unitCode'] + this.suggestion['roleId'] + '/');
    }

    /**删除岗位已经选中的人员信息 */
    deleteItem(item) {
        this.selectedNodes.forEach((ele, i) => {
            if (ele['id'] == item['id']) {
                this.selectedNodes.splice(i, 1);
                return;
            }
        });
        this.selectedRoleNodes.forEach((ele, i) => {
            if (ele['id'] == item['id']) {
                this.selectedRoleNodes.splice(i, 1);
                return;
            }
        });
    }
    /**递归展开查询的树 */
    recursionExpendSuggestionTreeNode(unitRoles: TreeNode[], roleCode: string) {
        unitRoles.forEach(ele => {
            let id = ele['id'];
            if (roleCode.indexOf('/' + id + '/') != -1) {
                if (roleCode == ele.data['code']) {
                    let notContain = true;
                    this.selectedNodes.forEach(sNode => {
                        if(ele['id'] == sNode['id']){
                            notContain = false;
                            return
                        }
                    })
                    if(notContain){
                        this.selectedNodes.push(ele); 
                        this.selectedRoleNodes.push(ele);
                    }
                    return
                }else{
                    ele.partialSelected = true;
                }
                //展开树节点
                ele.expanded = true;
                if (ele.children && ele.children.length > 0) {
                    this.recursionExpendSuggestionTreeNode(ele.children, roleCode);
                } else {
                    this.humanService.getUnitHumanTree(id, false).subscribe(nodes => {
                        ele.children = nodes;
                        this.recursionExpendSuggestionTreeNode(ele.children, roleCode);
                    });
                }
            } else {
                //关闭非节点
                ele.expanded = false;
            }
        })
    }
}
